package com.hczt.springcloud.oauthservice.config;

import com.hczt.springcloud.oauthservice.repository.UserRepository;
import com.hczt.springcloud.oauthservice.service.OAuthUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

/**
 * 精诚所至，金石为开。
 * 石の上にも三年;陽気の発する所金石亦透る。
 * Faith moves mountains.
 *
 * @author marvin.ma
 * @create 2017-12-11 23:14
 * @desc 配置认证管理器，以及安全策略
 * ①配置认证管理器（AuthenticationManagerBuilder）：
 * 两种方式：
        1. 配置固定用户名密码
        auth.inMemoryAuthentication()
        .withUser("user")  //用户名
        .password("user")//密码
        .roles("USER")//角色

        2. 通过实现userDetailsService接口类重写loadUserByUsername()方法返回UserDetails进行密码匹配
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
        auth.eraseCredentials(false);
        该密码加密方式为Springsecurity推荐的加密方式，放弃之前的PasswordEncoder改用BCryptPasswordEncoder()
 * ②配置安全策略（HttpSecurity）
 *
 **/
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    OAuthUserDetailsService oAuthUserDetailsService;

    @Autowired
    UserRepository userRepository;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //取消安全报文头 默认开启  可配置部分开启或全关
                //.headers().disable()
                //登录页面url 配置登录成功后调用的方法
                .formLogin().loginPage("/login").permitAll()
                //.successHandler(loginSuccessHandler())
                .failureUrl("/login?error")
                .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
                .authorizeRequests()
                //配置这些链接无需验证
                .antMatchers("/regist", "/toregist", "/public", "/oauth/token").permitAll()
                //除以上路径都需要验证
                .anyRequest().authenticated()
                //路径角色验证
                //.antMatchers("/admin/**").hasRole("ADMIN")
                //排除该路径角色认证  注意顺序自上而下
                //.antMatchers("/**").hasRole("USER")
                .and()
                //注销登录  默认支持 销毁session并且清空配置的rememberMe()认证 跳转登录页 或配置的注销成功页面
                .logout()
                .deleteCookies("remove")
                .invalidateHttpSession(false)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/logoutsuccess")
                .and()
                //http参数中包含一个名为“remember-me”的参数，不管session是否过期，用户记录将会被记保存下来
                .rememberMe()
                //.and()
                ////http映射https
                //.portMapper()
                //.http(8080).mapsTo(9443)
                .and()
                //配置http认证
                .httpBasic()
                //.and()
                //当用户进行重复登录时  强制销毁前一个登录用户  配置此应用必须添加Listener  HttpSessionEventPublisher
                //.sessionManagement()
                //.maximumSessions(1)
                //.expiredUrl("/login?expired")
        ;
    }

    @Autowired
    protected void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(oAuthUserDetailsService).passwordEncoder(passwordEncoder());
    }

    //不定义没有password grant_type
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
